package com.ttx.ch05;

import com.ttx.ch04.Dish;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

import static java.util.stream.Collectors.toList;

public class StreamFilterAndSlice {
    static List<Integer> integers = Arrays.asList(1, 2, 2, 5, 8, 8, 9, 11, 15, 4, 18, 5, 6, 90, 123, 43, 532, 520, 1314);

    public static void main(String[] args) {
        test1();
        System.out.println("--------------");
        test2();
        System.out.println("--------------");
        test3();
        System.out.println("--------------");
        test4();
        System.out.println("--------------");
        test5();
        System.out.println("--------------");
        test6();
        System.out.println("--------------");
        test7();
    }

    private static void test1() {
        integers.stream()
                .filter(integer -> integer % 2 == 0)
                .distinct()
                .forEach(System.out::println);
    }

    private static void test2() {
        integers.stream()
                .filter(integer -> integer % 2 == 0)
                .distinct()
                .skip(2) // 跳过最前面两个元素
                .forEach(System.out::println);
    }

    private static void test3() {
        // map函数为映射
        Dish.getDishs().stream()
                .map(Dish::getName)
                .map(String::length)
                .forEach(System.out::println);
    }

    private static void test4() {
        List<String> strings = Arrays.asList("Heollo", "World", "!");
        strings.stream()
                .map(s -> s.split(""))
                .flatMap(Arrays::stream)
                .forEach(System.out::println);
    }

    private static void test5() {
        String[] arrayOfWords = {"Goodbye", "World"};
        Stream<String> streamOfwords = Arrays.stream(arrayOfWords);

        List<String> collect = streamOfwords.map(word -> word.split(""))//将每个单词转换为由 其字母构成的数组
                .flatMap(Arrays::stream)
                //                .distinct()
                .collect(toList());
        System.out.println(collect);
    }

    private static void test6() {
        List<Integer> integers1 = Arrays.asList(1, 2, 4);
        List<Integer> integers2 = Arrays.asList(3, 5);
        final List<int[]> ints = integers1.stream()
                .flatMap(i1 -> integers2.stream().map(i2 -> new int[]{i1, i2}))
                .collect(toList());

        for (int[] i : ints) {
            System.out.println("<" + i[0] + "," + i[1] + ">");
        }
    }

    private static void test7() {
        List<Integer> integers1 = Arrays.asList(1, 2, 4);
        List<Integer> integers2 = Arrays.asList(3, 5);
        integers1.stream()
                .flatMap(i1 -> integers2.stream().map(i2 -> new int[]{i1, i2}))
                .map(pairs -> {
                    return "<" + pairs[0] + "," + pairs[1] + ">";
                })
                .forEach(System.out::println);

    }
}
